/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.component.jpanel;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.LayoutManager;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;
/**
 * 说明：
 * 以图片做背景的面板
 */
public class PicturePanel extends JPanel {

	private static final long serialVersionUID = 1L;

	/**
	 * 背景图片
	 */
	private Image image_bg=null;
	
	public PicturePanel() {}
	public PicturePanel(LayoutManager layout) {
		super(layout);
	}

	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		if(image_bg!=null){
			int pWidth = this.getWidth();
			int pHeight = this.getHeight();
			int mWidth = image_bg.getWidth(null);
			int mHeight = image_bg.getHeight(null);
			int x, y;
			int width, height;
			if ((mWidth <= pWidth) && (mHeight <= pHeight)) {
				x = (pWidth - mWidth) / 2;
				y = (pHeight - mHeight) / 2;
				width = mWidth;
				height = mHeight;
			} else {
				width = pWidth;
				height = pHeight;
				float widthScale = (float) pWidth / (float) mWidth;

				float heightScale = (float) pHeight / (float) mHeight;
				if (widthScale < heightScale)
					height = (int) (mHeight * widthScale);
				else
					width = (int) (mWidth * heightScale);
				x = (pWidth - width) / 2;
				y = (pHeight - height) / 2;
			}
			g.clearRect(0, 0, pWidth, pHeight);
			g.drawImage(image_bg, x, y, width, height, this);
		}
		
	}


	/**
	 * 根据传进来的图片布满，panel的背景，参数：图片
	 */
	public void setImage(Image img) {
		this.image_bg = img;
		this.repaint();
	}
	/**
	 * 根据传进来的图片布满，panel的背景,参数：图片路径
	 */
	public void setImage(String path) {
		try {
			image_bg = ImageIO.read(new File(path));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {

	}
}
